<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vuex-Getter</title>
    <script src="../../node_modules/vue/dist/vue.js"></script>
    <script src="../../node_modules/vuex/dist/vuex.min.js"></script>
</head>
<body>

<div id="app">
  <h2>{{msg}}</h2>
  <counter></counter>
  <a href="javascript:void(0);" @click="add">➕</a>
</div>

<script>
  // 定义一个组件
  const counter = {
    template:'<div>' +
      '<div>点击数量:{{count}}</div>' +
      '<div>用户名:{{userName}}</div>' +
      '</div>',
    computed:{
      count(){
        return this.$store.state.count;
      },
      name(){
        return this.$store.state.name;
      },
      userName(){
        return this.$store.getters.userName;
      }
    }
  };

  // 定义一个状态
  const store = new Vuex.Store({
    state: {
      count: 10,
      name: 'jack'
    },
    // 改变状态值
    mutations:{
      increment(state, num){
        state.count = num;
      },
      updateName(state, userName){
        state.name = userName;
      }
    },
    // 异步
    actions:{
      incrementAction(context, num){
        context.commit('increment', num);
      },
    },
    // 得到
    getters:{
      userName(state){
        return state.name + ',Hello';
      },
    }
  });

  new Vue({
    el:'#app',
    store,
    data:{
      msg:'Vuex的使用'
    },
    components:{
      counter
    },
    methods:{
      add(){
        this.$store.dispatch('incrementAction', 100);
      }
    }
  });
</script>
</body>
</html>
